package com.dream.common.advice;

import com.alibaba.fastjson.JSON;
import com.dream.common.annotation.ApiEncrypt;
import com.dream.common.encrypt.IEncryptService;
import com.dream.common.wrap.R;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @description: 接口返回参数加密控制器
 * @author: LiMG
 * @create: 2025-05-09 09:16:20
 **/
@Slf4j
@ControllerAdvice
public class ResponseBodyEncryptAdvice implements ResponseBodyAdvice<R> {

    @Resource
    private IEncryptService encryptService;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 判断方法或类上使用了ApiEncrypt注解
        return returnType.hasMethodAnnotation(ApiEncrypt.class) || returnType.getContainingClass().isAnnotationPresent(ApiEncrypt.class);
    }

    @Override
    public R beforeBodyWrite(R body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        Object data = body.getData();
        if (data == null) {
            return body;
        }
        String result = encryptService.encrypt(JSON.toJSONString(data));
        body.setData(result);
        return body;
    }

}
